/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 15:47:08
 * @Description: 法人信息审核状态
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  NativeModules,
  SafeAreaView,
  PixelRatio
} from 'react-native';
import { Button, msg, FormInput, cache } from '@/common';
import {
  px2dp, priceColor, mainBgColorWhite, fontColorBlack,
  fontColorDeepGray, mainBgColorLightGray,
} from '@/styles';
import { idCardFront, idCardBack, iconFailureTextRed } from '@/images';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import { uploadImage } from '@/config';
import businessApi from '@/api/business';
import AsyncStorage from '@react-native-community/async-storage';
import CameraCard from '../components/camera-card';
import BusinessDateItem from '../components/business-date-item';
import ExampleImager from './components/example-imager';

const { Submit } = Button;

export default class BusinessInfoCerti extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      longTimeChecked: false,
      selectDateChecked: false,
      isTimeShow: false,
      type: '居民身份证',
      name: '',
      idNo: '',
      validStartDate: '',
      validEndDate: '',
      identityCardFrontId: '',
      identityCardBackId: '',
      auditState: 2, // 审核状态
      reason: '',
      id: '',
      modalVisible: false
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.CURRENT_LEGAL).then((val) => {
      let currentLegal = JSON.parse(val);
      this.setState({ ...currentLegal }, () => {
        const { custId } = this.state;
        businessApi.getLegalIdCard({ custId }).then(res => {
          if (res.success && res.data) {
            this.setState({
              id: res.data.id,
              auditState: res.data.auditState,
              custId: res.data.custId,
              idNo: res.data.idNo,
              identityCardBackId: res.data.identityCardBackId,
              identityCardFrontId: res.data.identityCardFrontId,
              name: res.data.name,
              reason: res.data.reason,
              type: res.data.type,
              validEndDate: res.data.validEndDate,
              validStartDate: res.data.validStartDate,
              longTimeChecked: res.data.longTime == 1,
              selectDateChecked: res.data.longTime == 0,
            });
          }
        });
      });
    });
  }

  render() {
    const { type, name, idNo, longTimeChecked, isTimeShow, validStartDate, validEndDate,
      identityCardFrontId, identityCardBackId, auditState, reason, selectDateChecked, modalVisible } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          {
            auditState == 2 &&
            <View style={styles.reasonBox}>
              <Text style={styles.stepTip}> * 失败原因：</Text>
              <View style={{ flex: 1 }}>
                <Text style={styles.stepReason}>{reason}</Text>
              </View>
            </View>
          }
          <View style={styles.firstPart}>
            {auditState == 2 && <Image style={styles.dabiao} source={iconFailureTextRed} />}
            <FormInput
              label={<>
                <Text style={{ color: priceColor }}>&nbsp;&nbsp;</Text>
                <Text style={{ color: fontColorDeepGray }}>证件类型</Text>
              </>}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请选择证件类型'
              defaultValue={type}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('type', value);
              }}
              disabled={auditState != 2}
            />
            <FormInput
              label={this.formItem('姓名')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入姓名'
              defaultValue={name}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('name', value);
              }}
              disabled={auditState != 2}
            />

            <FormInput
              label={this.formItem('证件号码')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入证件号码'
              defaultValue={idNo}
              inputType={1}
              maxLength={18}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ minHeight: 60, borderBottomColor: 'transparent', paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('idNo', value);
              }}
              disabled={auditState != 2}
            />
            <BusinessDateItem
              disabled={auditState != 2}
              label='有效期限'
              selectDateChecked={selectDateChecked}
              longTimeChecked={longTimeChecked}
              onSwitchLongTime={this.switchChecked}
              onSwitchSelectDate={this.switchDateChecked}
              onStartDate={() => {
                this.setState({ isTimeShow: true, isTimeType: 'validStartDate' });
              }}
              onEndDate={() => {
                this.setState({ isTimeShow: true, isTimeType: 'validEndDate' });
              }}
              startTip={validStartDate}
              endTip={validEndDate}
            />

          </View>
          <View style={styles.licenseBox}>
            <View style={styles.labelBox}>
              {this.formItem('添加身份证')}
              {
                auditState == 2 &&
                <Text
                  style={styles.tempText}
                  onPress={this.checkTemp}
                >
                  查看示例
                </Text>
              }
            </View>
            <View style={styles.idcardBtnBox}>
              <CameraCard
                title='点击拍摄或上传人像面'
                type='identityCardFrontId'
                icon={identityCardFrontId}
                onCatchImage={(type) => this.selectImage(type)}
                bgImage={idCardFront}
              />
              <CameraCard
                title='点击拍摄或上传国徽面'
                type='identityCardBackId'
                icon={identityCardBackId}
                onCatchImage={(type) => this.selectImage(type)}
                bgImage={idCardBack}
              />
            </View>

          </View>
          {
            auditState == 2 &&
            <View style={styles.bottomBtnBox}>
              <View style={styles.submitBox}>
                <Submit
                  text='取消'
                  btnTextStyle={styles.preStepText}
                  boxStyle={styles.preBoxStyle}
                  onClick={this.goBack}
                />
              </View>
              <View style={styles.submitBox}>
                <Submit
                  text='重新提交'
                  btnTextStyle={styles.nextStepText}
                  boxStyle={styles.nextBoxStyle}
                  onClick={this.reSubmit}
                />
              </View>
            </View>
          }
          <DateTimePicker
            isVisible={isTimeShow}
            mode='date'
            cancelTextIOS='取消'
            confirmTextIOS='确认'
            headerTextIOS='选取日期'
            locale='zh_CN'
            onConfirm={(val) => {
              this.dateConfirm(val);
            }}
            onCancel={() => {
              this.dateCancel();
            }}
          />
          <ExampleImager
            type={2}
            modalVisible={modalVisible}
            onChange={this.checkTemp}
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  formItem = (name) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>{name}</Text>
      </>
    );
  }

  checkTemp = () => {
    const { modalVisible } = this.state;
    this.setState({
      modalVisible: !modalVisible,
    });
  }

  switchChecked = () => {
    const { longTimeChecked } = this.state;
    this.setState({ longTimeChecked: !longTimeChecked }, () => {
      const { longTimeChecked } = this.state;
      if (longTimeChecked) {
        this.setState({ selectDateChecked: false, validEndDate: '长期' });
      }
    });
  }

  // 选择日期
  switchDateChecked = () => {
    const { selectDateChecked } = this.state;
    this.setState({ selectDateChecked: !selectDateChecked, longTimeChecked: false }, () => {
      const { selectDateChecked } = this.state;
      if (!selectDateChecked) {
        this.setState({ validStartDate: '', validEndDate: '' });
      } else {
        this.setState({ validEndDate: '' });
      }
    });
  }

  goBack = () => {
    msg.emit('router: back');
  }

  reSubmit = () => {
    const { type, name, idNo, longTimeChecked, validStartDate, validEndDate,
      identityCardFrontId, identityCardBackId, custId, selectDateChecked, id } = this.state;
    if (!type) return msg.emit('app:tip', { text: '请选择证件类型' });
    if (!name) return msg.emit('app:tip', { text: '请填写用户姓名' });
    if (!idNo) return msg.emit('app:tip', { text: '请填写证件号码' });
    if ((!validStartDate || !validEndDate) && !longTimeChecked) return msg.emit('app:tip', { text: '请选择有效期限' });
    if (longTimeChecked && !validStartDate) return msg.emit('app:tip', { text: '请选择有效期限起始日期' });
    if (!identityCardFrontId) return msg.emit('app:tip', { text: '请上传证件照正面' });
    if (!identityCardBackId) return msg.emit('app:tip', { text: '请上传证件照背面' });

    const legalInfoCertiParams = {
      id,
      type,
      name,
      idNo,
      validStartDate,
      validEndDate,
      longTimeChecked, // 是否选择长期
      selectDateChecked,
      longTime: longTimeChecked ? 1 : 0,
      identityCardFrontId,
      identityCardBackId,
      custId
    };
    businessApi.updateLegalIdCard(legalInfoCertiParams).then(res => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        msg.emit('router: refreshRoute', {
          routeName: 'BusinessData',
        });
        msg.emit('router: goToNext', {
          routeName: 'BusinessData',
          custId
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 日期选择后确认
  dateConfirm = (date) => {
    const { isTimeType } = this.state;
    this.setState({ [isTimeType]: Moment(date).format('YYYY-MM-DD') });
    this.setState({ isTimeShow: false });
  }

  // 隐藏日期选择器
  dateCancel = () => {
    this.setState({ isTimeShow: false });
  };

  // 选择图片
  selectImage = imgType => {
    const { auditState } = this.state;
    if (auditState != 2) return;
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(imgType, path);
    });
  }

  // 上传图片
  IdCardUpload(imgType, path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    uploadImage('upload?dirName=businessCert', path).then(res => {
      if (res.success) {
        if (imgType == 'identityCardFrontId') {
          this.setState({ identityCardFrontId: res.data.url });
        }
        if (imgType == 'identityCardBackId') {
          this.setState({ identityCardBackId: res.data.url });
        }
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传失败，请重试',

          isClickBg: false,
          okFn: () => { },
        });
      }
      msg.emit('app:selfTip', {
        isVisible: false,
      });
    }).catch(err => {
      console.log(err);
      msg.emit('app:selfTip', {
        isVisible: false,
      });
      // 请求失败
      msg.emit('app:messageBox', {
        isVisible: true,
        title: '温馨提示',
        text: '上传失败，请重试',

        isClickBg: false,
        okFn: () => { },
      });
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray
  },
  reasonBox: {
    backgroundColor: '#FFF5F5',
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24),
    flexDirection: 'row'
  },
  stepTip: {
    color: '#EB2F2F',
    fontSize: px2dp(28),
  },
  stepReason: {
    color: '#EB2F2F',
    fontSize: px2dp(28),
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    flexWrap: 'wrap'
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingBottom: px2dp(60)
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40)
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38)
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline'
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130)
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40)
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16)
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190)
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10)
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16)
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16)
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  idcardBtnBox: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: px2dp(40),

  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48)
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: px2dp(40),
    height: px2dp(200)
  },
  submitBox: {
    flex: 1,
    alignItems: 'center'
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764'
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5'
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%'
  },
  dabiao: {
    position: 'absolute',
    width: px2dp(151),
    height: px2dp(114),
    right: px2dp(32),
    top: px2dp(25),
    zIndex: 1
  }
});
